﻿Option Explicit On
Imports System.IO
Imports System.Net
Imports System.ComponentModel

Public Class frmmain

    'Extract option varibale.
    Private ExtractOption As Byte = 0
    Private IsDone As Boolean = False
    Private TAddress As Uri = Nothing
    Private cCfg As New mycfg()

    Private Function FileFromDlg(ByVal iFilename As String) As String
        Dim sd As New SaveFileDialog()

        With sd
            .Title = "Save To"
            .FileName = iFilename
            If .ShowDialog().Equals(DialogResult.OK) Then
                Return .FileName
            End If
        End With

        Return vbNullString
    End Function

    Private Sub ProjectError(ByVal message As String, Optional ByVal title As String = vbNullString)
        MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Sub

    Private Sub Client_ProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
        lblStatus.Text = "Status: Please wait downloading...."
    End Sub

    Private Sub Client_DownloadFileCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
        lblStatus.Text = "Status: Download complete..."
    End Sub

    Private Sub DownloadTo(ByVal Address As Uri, ByVal Filename As String)
        Dim wc As New System.Net.WebClient()
        'Add event handlers.
        AddHandler wc.DownloadProgressChanged, AddressOf Client_ProgressChanged
        AddHandler wc.DownloadFileCompleted, AddressOf Client_DownloadFileCompleted
        'Download the file.
        wc.DownloadFileAsync(Address, Filename)
    End Sub

    Private Sub GetLinks(ByRef LItem As List(Of String), ByVal FileType As String)
        'Extract all links store into list object.
        Dim Ext As String = vbNullString
        Dim sPos As Integer = -1

        For Each HtmlE As HtmlElement In WB.Document.Links
            Dim hLink As String = HtmlE.GetAttribute("href")

            'Check for empty string.
            If Not String.IsNullOrEmpty(hLink) Then
                'Check for filters.
                If (FileType.Equals("all")) Then
                    'Add hLink
                    LItem.Add(hLink)
                Else
                    'Get last position of .
                    sPos = hLink.LastIndexOf(".")

                    If (sPos <> -1) Then
                        Ext = hLink.Substring(sPos + 1).ToLower()
                        'Check for ext match.
                        If Ext.Equals(FileType) Then
                            LItem.Add(hLink)
                        End If
                    End If
                End If
            End If

        Next HtmlE
    End Sub

    Private Sub GetImages(ByRef LItem As List(Of String), ByVal FileType As String)
        'Extract all links store into list object.
        Dim Ext As String = vbNullString
        Dim sPos As Integer = -1

        For Each HtmlE As HtmlElement In WB.Document.All
            Dim hLink As String = HtmlE.GetAttribute("src")

            'Check for empty string.
            If Not String.IsNullOrEmpty(hLink) Then
                'Check for filters.
                If (FileType.Equals("all")) Then
                    'Add hLink
                    LItem.Add(hLink)
                Else
                    'Get last position of .
                    sPos = hLink.LastIndexOf(".")

                    If (sPos <> -1) Then
                        Ext = hLink.Substring(sPos + 1).ToLower()
                        'Check for ext match.
                        If Ext.Equals(FileType) Then
                            LItem.Add(hLink)
                        End If
                    End If
                End If
            End If
        Next HtmlE
    End Sub

    Private Sub GetEmails(ByRef LItem As List(Of String))
        'Extract all links store into list object.
        For Each HtmlE As HtmlElement In WB.Document.All
            Dim hLink As String = HtmlE.GetAttribute("href")
            'Check for empty string.
            If Not String.IsNullOrEmpty(hLink) Then
                If hLink.StartsWith("mailto".ToLower()) Then
                    LItem.Add(hLink)
                End If
            End If
        Next HtmlE
    End Sub

    Private Sub frmmain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If (WB.ReadyState <> WebBrowserReadyState.Complete) Then
            WB.Stop()
        End If
    End Sub

    Private Sub frmmain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim cfgFile As String = Path.Combine(Application.StartupPath, "config.cfg")

        'Add default item.
        cboFilter.Items.Add("all")

        If File.Exists(cfgFile) Then
            'Load config filename.
            cCfg.Filename = Path.Combine(Application.StartupPath, "config.cfg")
            'Read config file.
            cCfg.ReadConfig()
            'Set combo index.
            cboType.SelectedIndex = 0
        End If

    End Sub

    Private Sub cmdExtract_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExtract.Click
        Dim Items As New List(Of String)

        If txtAddress.Text.Equals(String.Empty) Then
            ProjectError("Please enter a web address.", "No Address Found")
            txtAddress.Focus()
        Else
            'Clear listbox.
            LstItems.Items.Clear()
            'Goto the web address.
            WB.Navigate(txtAddress.Text)

            'Update status text.
            lblStatus.Text = "Status: Please wait extracting links..."

            'Make sure eveything finishes.
            Try

                Do While WB.IsBusy = True
                    Application.DoEvents()
                Loop

                Do While WB.ReadyState <> WebBrowserReadyState.Complete
                    Application.DoEvents()
                Loop

            Catch ex As Exception
                ProjectError(ex.Message)
            End Try

            Select Case ExtractOption
                Case 0
                    'Get links.
                    GetLinks(Items, cboFilter.Text)
                Case 1
                    'Get images.
                    GetImages(Items, cboFilter.Text)
                Case 2
                    'Get emails.
                    GetEmails(Items)
            End Select

            'Remove duplicates.
            Items = Items.Distinct().ToList

            'Add items to listbox.
            LstItems.Items.AddRange(Items.ToArray)

            'Update status text.
            lblStatus.Text = "Status: Finished..."

            'Update groupbox text.
            G2.Text = "Result Found: " & LstItems.Items.Count
        End If

    End Sub

    Private Sub cboType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboType.SelectedIndexChanged
        Dim ftypes As New List(Of String)

        'Set extact type.
        ExtractOption = CType(cboType.SelectedIndex, Byte)

        'Clear combo box.
        cboFilter.Items.Clear()

        'Add default item.
        cboFilter.Items.Add("all")

        cboFilter.Enabled = (ExtractOption <> 2)

        If (ExtractOption = 0) Then
            'Add filter file types
            cCfg.ReadList("filetypes", ftypes)
        End If

        If (ExtractOption = 1) Then
            'Add image filter types
            cCfg.ReadList("imagetypes", ftypes)
        End If

        'Add to combobox.
        cboFilter.Items.AddRange(ftypes.ToArray)
        cboFilter.SelectedIndex = 0

    End Sub

    Private Sub cmdAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAbout.Click
        'Display info box.
        MessageBox.Show(Text & " Version 1.1" & vbCrLf & vbTab & " By Ben Jones" & vbCrLf & "Hope You Like It.", "About" _
                        , MessageBoxButtons.OK, MessageBoxIcon.Information)
    End Sub

    Private Sub cmdClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdClose.Click
        'Close program.
        Close()
    End Sub

    Private Sub cmdDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDownload.Click
        Dim Item As String = vbNullString
        Dim sFile As String = vbNullString

        Try
            Item = LstItems.SelectedItem.ToString()
            'Build address.
            TAddress = New Uri(Item)
            'Get filename from dialog.
            sFile = FileFromDlg(Path.GetFileName(TAddress.LocalPath))
            'Check for empty string.
            If sFile.Equals(String.Empty) Then
                ProjectError("Please enter a vaild filename.", "No Name Found")
            Else
                'Download and save file.
                DownloadTo(TAddress, sFile)
            End If

        Catch ex As Exception
            ProjectError("No item selected for download." _
                         , "No Item Selected")
        End Try
    End Sub

    Private Sub WB_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WB.DocumentCompleted

    End Sub
End Class
